<template>
  <div id="headerText" class="header-text">
    {{ title }}
    <div v-if="showLogo" class="logo-img"><img src="../../assets/img/logo.png" alt=""></div>
  </div>

</template>

<script setup>
import _ from 'lodash'

defineOptions({
  name: 'HeaderText'
})
const props = defineProps({
  showLogo: {
    type: Boolean,
    default: false
  },
  fontSize: {
    type: Number,
    default: 14
  }
})
let resizeObserver = null
const state = reactive({
  textWidth: '',
  textLen: ''
})
const appStore = useAppStore()
const title = computed(() => {
  return appStore.appTitle || '智慧交通综合管控平台'
})
onMounted(() => {
  nextTick(() => {
    autoFontSize()
  })
})
onUnmounted(() => {
  resizeObserver.disconnect()
  resizeObserver = null
})
// 监听尺寸变化
const addResizeListen = (dom, callback) => {
  resizeObserver = new ResizeObserver(entries => {
    if (callback) callback(entries)
  })
  resizeObserver.observe(dom)
}
const autoFontSize = () => {
  const el = document.getElementById('headerText')
  state.textLen = fontUtils.getStringLength(title.value)
  state.textWidth = state.textLen * props.fontSize
  let boxWidth = document.getElementById('headerText').offsetWidth
  compileWidth(state.textWidth, boxWidth)
  if (el) {
    addResizeListen(el, _.debounce((entries) => {
      const width = entries[0].contentRect.width
      compileWidth(state.textWidth, width)
    }, 500))
  }
}
const compileWidth = (textWidth, boxWidth) => {
  const el = document.getElementById('headerText')
  if (!el) return
  if (textWidth > boxWidth) {
    el.style.fontSize = Math.floor(boxWidth / state.textLen) + 'px'
    el.style.height = Math.floor(boxWidth / state.textLen) + 'px'
  } else {
    el.style.fontSize = props.fontSize + 'px'
    el.style.height = props.fontSize + 'px'
  }
}
</script>
<style lang="scss" scoped>
.header-text {
  position: relative;
  width: 100%;
  margin: 0 auto;
  font-family: 'FZMHK',serif;
  font-size: 0;
  //background-image: linear-gradient(to bottom, #2088df, #23a8df);
  background-image: linear-gradient(180deg, #d628fe, #35a2fd);
  -webkit-background-clip: text; /* 背景被裁剪成文字的前景色 */
  -webkit-text-fill-color: transparent; /* 文字填充颜色变透明 */
  letter-spacing: -1.6px;
  display: flex;
  justify-content: center;

  .logo-img {
    position: absolute;
    right: -38%;
    top: -10px;
    width: 30px;
    height: 30px;

    img {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
